package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;

    private ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();

     @Autowired
     CartFeignService cartFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }



    //确认订单
    @Override
    public OrderConfirmVo confirm() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
        //把主线程的请求，共享给两个子线程
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1. 远程查询所有的收货地址
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
                    List<MemberAddressVo> address = memberFeignService.getAddress(memberResVo.getId());
                    orderConfirmVo.setAddress(address);
                }
                , threadPoolExecutor);



        //2.远程查询购物车的所有选中项

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItems = cartFeignService.currentUserCartItems();
            orderConfirmVo.setItems(orderItems);

        }, threadPoolExecutor).thenRunAsync(()->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item ->
                    item.getSkuId()
            ).collect(Collectors.toList());

            System.out.println(collect);
            //远程查询是否有库存
            R skusHasStock = wareFeignService.getSkusHasStock(collect);
            Object data = skusHasStock.get("data");
            String s = JSON.toJSONString(data);
            List<SkuHasStockVo> skuHasStocks = JSON.parseObject(s, new TypeReference<List<SkuHasStockVo>>(){});

            Map<Long, Boolean> map = skuHasStocks.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            System.out.println(map);
            orderConfirmVo.setHasStock(map);


        },threadPoolExecutor);

        //查询用户积分
        Integer integration = memberResVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

       CompletableFuture.allOf(addressFuture,cartFuture).get();

        // 防止重复提交

        String token = UUID.randomUUID().toString().replace("-","");
         redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResVo.getId(),token);
         orderConfirmVo.setOrderTokern(token);

        return orderConfirmVo;
    }


    // 提交订单  去结算方法
    @Override
    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {

        threadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0);
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();

        //下单 去创建订单
        String orderToken = orderSubmitVo.getOrderToken();
//        String token = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId());

        String script ="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId()), orderToken);

        if(execute == 0L){
            response.setCode(1);
            return response;
        }else{
            //原子令牌 验证成功
            //下单

            OrderCreateVo orderCreateVo = orderCreateVo();

            //验证价格
            BigDecimal payAmount = orderCreateVo.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();

            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //3. 保存订单
                saveOrder(orderCreateVo);

                //4. 锁定库存
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(orderCreateVo.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = orderCreateVo.getOrderItems().stream().map(item -> {
                    OrderItemVo itemvo = new OrderItemVo();
                    itemvo.setSkuId(item.getSkuId());
                    itemvo.setCount(item.getSkuQuantity());
                    itemvo.setTitle(item.getSkuName());
                    return itemvo;
                }).collect(Collectors.toList());

                lockVo.setLocks(orderItemVos);

                R r = wareFeignService.orderLockStock(lockVo);
                if(r.getCode() == 0){
                    //锁定库存成功
                   // int n = 10/0;
                    response.setOrder(orderCreateVo.getOrder());
                    //订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateVo.getOrder());
                    return response;
                }else{
                  //锁定失败
             ///     throw new NoStockException();
                    response.setCode(3);
                    return response;
                }


            }else{
                //价格 与加入购物车价格不符合
                response.setCode(2);
             return response;
            }

        }

    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        return order_sn;
    }

    //订单时间到了，准备关闭订单
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());

        if(orderEntity.getStatus()  == OrderStatusEnum.CREATE_NEW.getCode()){
            //关闭订单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);

            //发送mq一个消息，通知库存释放
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other", orderTo);

        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);

        payVo.setTotal_amount(bigDecimal.toString());
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));

        OrderItemEntity orderItemEntity = order_sn.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setOut_trade_no(orderSn);
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberResVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItems(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);

    }

    /**
     * 处理支付宝的结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setTotalAmount(new BigDecimal(vo.getTotal_amount()));
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoEntity.setSubject(vo.getSubject());

        paymentInfoService.save(paymentInfoEntity);

        //修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());

        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal total = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal(seckillOrderTo.getNum()));
        orderEntity.setPayAmount(total);

        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(total);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(orderItemEntity);
    }

    //保存订单
    private void saveOrder(OrderCreateVo orderCreateVo) {

        OrderEntity order = orderCreateVo.getOrder();
        order.setModifyTime(new Date());
        this.save(order);

        //保存订单项

        List<OrderItemEntity> orderItems = orderCreateVo.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    //创建订单
    private OrderCreateVo orderCreateVo(){

        OrderCreateVo orderCreateVo = new OrderCreateVo();
         //生成订单号
        String timeId = IdWorker.getTimeId();
        //构建订单
        OrderEntity orderEntity = buildOrderEntity(timeId);

        //构建所有订单项
        List<OrderItemEntity> itemEntities = buildOrderItemEntity(timeId);

        //3. 计算价格
      computePrice(orderEntity,itemEntities);
      orderCreateVo.setOrder(orderEntity);
      orderCreateVo.setOrderItems(itemEntities);
        return orderCreateVo;

    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {

        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift  = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        for (OrderItemEntity itemEntity : itemEntities) {
            BigDecimal realAmount =itemEntity.getRealAmount();
            integration = integration.add(itemEntity.getIntegrationAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            coupon = coupon.add(itemEntity.getCouponAmount());

            gift = gift.add(new BigDecimal(itemEntity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(itemEntity.getGiftGrowth().toString()));
            total = total.add(realAmount);
        }
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegration(integration.intValue());
        orderEntity.setCouponAmount(coupon);

        //设置积分 成长值
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setDeleteStatus(0);//未删除


    }

    private List<OrderItemEntity> buildOrderItemEntity(String timeId){

        //获取所有的购物项
        List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();

        if(orderItemVos !=null&&orderItemVos.size()>0){
            List<OrderItemEntity> itemEntities = orderItemVos.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(timeId);
                orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
                return orderItemEntity;
            }).collect(Collectors.toList());

            return itemEntities;
        }

        return null;
    }

    //构建某个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //商品的spu信息
        R r = productFeignService.getSpuBySkuId(cartItem.getSkuId());
        Object spu = r.get("spu");
        String spuJson = JSON.toJSONString(spu);
        SpuInfoVo spuInfoVo = JSON.parseObject(spuJson, SpuInfoVo.class);
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());


        //商品sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuPic(cartItem.getImage());
        String s = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(s);
        orderItemEntity.setSkuQuantity(cartItem.getCount());

        //积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //订单项的价格
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        origin = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(origin);

        return orderItemEntity;



    }

    private OrderEntity buildOrderEntity(String timeId){
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();

        OrderSubmitVo orderSubmitVo = threadLocal.get();


        //创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(timeId);
        orderEntity.setMemberId(memberResVo.getId());
        orderEntity.setMemberUsername(memberResVo.getNickname());
        orderEntity.setCreateTime(new Date());
        //设置订单状态为待付款
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());


        //获取收货地址信息
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());

        Object data = fare.get("data");
        String s = JSON.toJSONString(data);
        FareVo fareVo = JSON.parseObject(s, FareVo.class);
        orderEntity.setFreightAmount(fareVo.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareVo.getAddress().getCity());
        orderEntity.setReceiverName(fareVo.getAddress().getName());
        orderEntity.setReceiverProvince(fareVo.getAddress().getProvince());
        orderEntity.setReceiverPhone(fareVo.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        orderEntity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        orderEntity.setReceiverRegion(fareVo.getAddress().getRegion());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());

        System.out.println("创建订单：" + format);
        return  orderEntity;
    }

}